
#include "WiFiClient.h"
#include "WiFiUdp.h"

#include <Wire.h>
#include <time.h>



#include "oled.h"
#include "ESP8266WiFi.h"
#include "NET_Ctrl.h"



unsigned int localPort = 2390; 

const char* ntpServerName = "time1.aliyun.com";
IPAddress timeServerIP;
const int NTP_PACKET_SIZE = 48;                     // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[NTP_PACKET_SIZE];                 // buffer to hold incoming and outgoing packets


WiFiUDP udp;


unsigned long epoch = 0;



String ip2Str(IPAddress ip) { //IP地址转字符串
    String s = "";
    for (int i = 0; i < 4; i++) {
        s += i ? "." + String(ip[i]) : String(ip[i]);
    }
    return s;
}



void scanwif2OLED()
{
    char msg[20];

    int n = WiFi.scanNetworks();
    if (n == 0) 
    {
        OLED_Debug("no font WIFI",1,16);
    }
    else 
    {
        for (int i = 0; i < n; ++i) 
        {           
            WiFi.SSID(i).toCharArray(msg,9);
            OLED_Debug(msg,1,16);
            delay(1000);
        }
         OLED_Debug("scan done",0,16);
    }
}



bool autoConfig(const char* ssid,const char* passwd)
{
    char msg[20];
    OLED_Debug("Connect..",0,16);
    OLED_Debug((char*)ssid,1,16);
    WiFi.begin(ssid,passwd);                    // 默认连接保存的WIFI

    for (int i = 0; i < 30; i++)
    {

       if (WiFi.status() == WL_CONNECTED)
       {
            Serial.println("AutoConfig Success");
            Serial.printf("SSID:%s\r\n", WiFi.SSID().c_str());
            Serial.printf("PSW:%s\r\n", WiFi.psk().c_str());

            Serial.println("WiFi connected");
            Serial.println(WiFi.localIP());
            Serial.println("Starting UDP");
            OLED_Debug("OK!!",0,16);
            OLED_Debug((char*)ip2Str(WiFi.localIP()).c_str(),1,12);
            udp.begin(localPort);
            Serial.print("Local port: ");
            Serial.println(udp.localPort());
            return true;
       }
       else{
            Serial.print("AutoConfig Waiting......");
            Serial.println(WiFi.status());
            sprintf(msg,"time:%d!",i);
            OLED_Debug(msg,1,16);
            delay(200);
       }
    }

    Serial.println("AutoConfig Faild!" );
    OLED_Debug("AutoConfig Faild!",1,16);
    return false;
}



tm* connectNTP() { //if response from NTP was succesfull return *tm else return a nullpointer
    WiFi.hostByName(ntpServerName, timeServerIP);
    Serial.println(timeServerIP);
    Serial.println("sending NTP packet...");
    // set all bytes in the buffer to 0
    memset(packetBuffer, 0, NTP_PACKET_SIZE);
    // Initialize values needed to form NTP request
    // (see URL above for details on the packets)
    packetBuffer[0] = 0b11100011;   // LI, Version, Mode
    packetBuffer[1] = 0;     // Stratum, or type of clock
    packetBuffer[2] = 6;     // Polling Interval
    packetBuffer[3] = 0xEC;  // Peer Clock Precision
    // 8 bytes of zero for Root Delay & Root Dispersion
    packetBuffer[12] = 49;
    packetBuffer[13] = 0x4E;
    packetBuffer[14] = 49;
    packetBuffer[15] = 52;
    // all NTP fields have been given values, now
    // you can send a packet requesting a timestamp:
    udp.beginPacket(timeServerIP, 123); //NTP requests are to port 123
    udp.write(packetBuffer, NTP_PACKET_SIZE);
    udp.endPacket();
    delay(1000);                 // wait to see if a reply is available
    int cb = udp.parsePacket();
    udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:
    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    // now convert NTP time into everyday time:
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:
    epoch = secsSince1900 - seventyYears + 3600*8 + 2; //+2000ms Verarbeitungszeit
    //epoch=epoch-3600*6; // difference -6h = -6* 3600 sec)
    time_t t;
    t = epoch;
    tm* tt;
    tt = localtime(&t);
    Serial.println(epoch);
    Serial.println(asctime(tt)); 
    if (cb == 48)
        return (tt);
    else
        return (NULL);
}






